import { IconMoon, IconSun } from "@douyinfe/semi-icons";
import { Nav, Typography, Space, Notification } from "@douyinfe/semi-ui";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { Input, Modal, Avatar, Button, Text } from "@nextui-org/react";
import { useTheme as useNextTheme } from "next-themes";
import { useTheme } from "@nextui-org/react";
import IconPassword from "./icon-password";
import IconUser from "./icon-user";
import { BASEURL } from "../utils/config";
import swr from "./swr";

export default function HeaderNav() {
  const { Title } = Typography;
  const router = useRouter();
  const [defaultIsCollapsed, setDefaultIsCollapsed] = useState(false);
  const [showLogin, setShowLogin] = useState(false);
  const [shouldLogin, setShouldLogin] = useState(false);
  const [loginData, setLoginData] = useState({
    grant_type: "password",
    username: "",
    password: "",
    client_id: "",
    client_secret: "",
  });
  const { setTheme } = useNextTheme();
  const { isDark } = useTheme();
  const { data, isLoading, isError } = swr("/me");
  const emptyData = {
    name: "",
    id_number: "",
    password: "",
    phone_number: "",
    sex: "",
    subject: "",
    classes: [],
  };
  const [userData, setUserData] = useState(emptyData);
  if (!isLoading && (isError || typeof data.detail !== "undefined")) {
    if (!shouldLogin) {
      setShouldLogin(true);
      setShowLogin(true);
    }
  } else if (userData == emptyData || userData != data) {
    setUserData(data);
  }
  useEffect(() => {
    if (window.matchMedia("(orientation: portrait)").matches) {
      setDefaultIsCollapsed(false);
    }
    if (isDark) {
      document.body.setAttribute("theme-mode", "dark");
    } else if (document.body.hasAttribute("theme-mode")) {
      document.body.removeAttribute("theme-mode");
    }
  });

  return (
    <>
      <Nav
        defaultIsCollapsed={defaultIsCollapsed}
        mode="horizontal"
        onClick={(data) => router.push(data.itemKey)}
      >
        <Nav.Header>
          <Title
            link={{ href: "/" }}
            style={{
              fontSize: "1.3em",
            }}
          >
            成绩管理系统
          </Title>
        </Nav.Header>
        <Nav.Item itemKey={"/register"}>成绩登记</Nav.Item>
        <Nav.Item itemKey={"/query"}>成绩查询</Nav.Item>
        <Nav.Footer>
          <Space>
            <Button
              auto
              onClick={() => {
                setTheme(isDark ? "light" : "dark");
              }}
              icon={isDark ? <IconMoon /> : <IconSun />}
            ></Button>
            <Avatar
              squared
              onClick={() => {
                setShowLogin(true);
              }}
              text={(() => {
                if (isLoading || shouldLogin || !userData) {
                  return "";
                } else {
                  if (userData.name) {
                    return userData.name == "admin" ? "管理员" : userData.name;
                  } else {
                    return "";
                  }
                }
              })()}
            ></Avatar>
          </Space>
        </Nav.Footer>
      </Nav>
      <Modal
        closeButton={!shouldLogin}
        preventClose={shouldLogin}
        aria-labelledby="登陆"
        open={showLogin}
        onClose={() => {
          setShowLogin(false);
        }}
      >
        <Modal.Header>
          <Text b size={18} css={{ paddingTop: 10 }}>
            {!shouldLogin ? "重新登陆" : "登陆"}
          </Text>
        </Modal.Header>
        <Modal.Body>
          <Input
            bordered
            fullWidth
            color="primary"
            size="lg"
            aria-label="用户名"
            placeholder="用户名"
            type="text"
            contentLeft={<IconUser />}
            onChange={(e) => {
              setLoginData({
                ...loginData,
                username: e.target.value,
              });
            }}
          />
          <Input
            bordered
            fullWidth
            color="primary"
            size="lg"
            aria-label="密码"
            placeholder="密码"
            type="password"
            contentLeft={<IconPassword />}
            onChange={(e) => {
              setLoginData({
                ...loginData,
                password: e.target.value,
              });
            }}
          />
        <Text size={13}>测试用户名：admin</Text>
        <Text size={13}>测试密码：adminpassword</Text>
        </Modal.Body>
        <Modal.Footer>
          {!shouldLogin ? (
            <>
              <Button
                auto
                flat
                color="warning"
                onClick={() => {
                  localStorage.clear();
                  location.reload();
                }}
              >
                退出登陆
              </Button>
              <Button
                auto
                flat
                color="error"
                onClick={() => {
                  setShowLogin(false);
                }}
              >
                <Text>取消</Text>
              </Button>
            </>
          ) : null}
          <Button
            auto
            onClick={() => {
              fetch(`${BASEURL}/login`, {
                method: "POST",
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
                body: new URLSearchParams(loginData).toString(),
              })
                .then((res) => res.json())
                .then((data) => {
                  if (data.access_token) {
                    localStorage.setItem("token", data.access_token);
                    Notification.success({
                      content: "登陆成功",
                    });
                    location.reload();
                  } else {
                    Notification.error({
                      content: "登陆失败",
                    });
                  }
                })
                .catch((err) => {
                  Notification.error({
                    content: `登陆失败 ${err}`,
                  });
                });
            }}
          >
            <Text>登陆</Text>
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}
